import axios from 'axios';
import type { AxiosInstance } from 'axios';
import type { LoginRequest, RegisterRequest, AuthResponse } from '../types';

class ApiClient {
  private client: AxiosInstance;
  private token: string | null = null;

  constructor() {
    this.client = axios.create({
      baseURL: import.meta.env.VITE_API_BASE_URL || 'http://localhost:8000',
      timeout: 10000,
      headers: {
        'Content-Type': 'application/json',
      },
    });

    // 请求拦截器 - 添加认证token
    this.client.interceptors.request.use(
      (config) => {
        if (this.token) {
          config.headers.Authorization = `Bearer ${this.token}`;
        }
        return config;
      },
      (error) => {
        return Promise.reject(error);
      }
    );

    // 响应拦截器 - 处理错误
    this.client.interceptors.response.use(
      (response) => response,
      (error) => {
        if (error.response?.status === 401) {
          // 清除token，但不自动跳转，让组件处理错误显示
          this.setToken(null);
        }
        return Promise.reject(error);
      }
    );
  }

  setToken(token: string | null) {
    this.token = token;
    if (token) {
      localStorage.setItem('token', token);
    } else {
      localStorage.removeItem('token');
    }
  }

  getToken(): string | null {
    if (!this.token) {
      this.token = localStorage.getItem('token');
    }
    return this.token;
  }

  // 用户认证
  async login(data: LoginRequest): Promise<AuthResponse> {
    const response = await this.client.post<AuthResponse>('/api/users/login', data);
    this.setToken(response.data.access_token);
    return response.data;
  }

  async register(data: RegisterRequest): Promise<AuthResponse> {
    const response = await this.client.post<AuthResponse>('/api/users/register', data);
    this.setToken(response.data.access_token);
    return response.data;
  }

  async getCurrentUser() {
    const response = await this.client.get('/api/users/me');
    return response.data;
  }

  // 知识库管理
  async getKnowledgeBases() {
    const response = await this.client.get('/api/knowledge-bases/');
    return response.data;
  }

  async createKnowledgeBase(data: any) {
    const response = await this.client.post('/api/knowledge-bases/', data);
    return response.data;
  }

  async updateKnowledgeBase(id: number, data: any) {
    const response = await this.client.put(`/api/knowledge-bases/${id}`, data);
    return response.data;
  }

  async deleteKnowledgeBase(id: number) {
    const response = await this.client.delete(`/api/knowledge-bases/${id}`);
    return response.data;
  }

  // MCP服务管理
  async getMcpServices() {
    const response = await this.client.get('/api/mcp-services/');
    return response.data;
  }

  async createMcpService(data: { name: string; description: string; server_url: string }) {
    const mcpData = {
      name: data.name,
      description: data.description,
      service_type: 'http',
      config: JSON.stringify({ server_url: data.server_url }),
      knowledge_base_id: 1 // 临时使用第一个知识库
    };
    const response = await this.client.post('/api/mcp-services/', mcpData);
    return response.data;
  }

  async updateMcpService(id: number, data: any) {
    const response = await this.client.put(`/api/mcp-services/${id}`, data);
    return response.data;
  }

  async deleteMcpService(id: number) {
    const response = await this.client.delete(`/api/mcp-services/${id}`);
    return response.data;
  }

  // 对话记录管理
  async getConversations(knowledgeBaseId?: number) {
    const params = knowledgeBaseId ? { knowledge_base_id: knowledgeBaseId } : {};
    const response = await this.client.get('/api/conversations/', { params });
    return response.data;
  }

  async createConversation(data: any) {
    const response = await this.client.post('/api/conversations/', data);
    return response.data;
  }

  async deleteConversation(id: number) {
    const response = await this.client.delete(`/api/conversations/${id}`);
    return response.data;
  }
}

export const apiClient = new ApiClient();
export default apiClient;